#include"sock_init.h"

#define IPS    "ips="
#define PORT   "port="
#define LISMAX "lismax="



struct sock_info//定义一个结构用来存放信息
{
    char ips[36];//127.0.0.1
    short port;
    int lismax;
};

int read_sock_conf(struct sock_info*dt)//将配置文件中的信息读取给dt
{
    if(dt==NULL)
    {
         return -1;
    }
    //以只读方式打开配置文件
    FILE*fp=fopen("socket_info.conf","r");
    if(fp==NULL)
    {
         printf("open socket_info.conf failed\n");
         return -1;
    }   

    //一次读取一行
    //遇见“#” ，continue,跳过，因为是注释
    //遇见空行，跳过
    
    int index=0;
    while(1)
    {
        char buff[128]={0};
        char*s=fgets(buff,128,fp);//从fp中计划读取128个字节放在buff中。fgets成功的返回值就是buff，相当于让s指向了buff
        if(s==NULL)//fp读到末尾了
        {
            break;
        }
        index++;//记录行号
        if(s[0]=='#'||s[0]=='\n')//s[0]==buff[];
        {
            continue;
        }
        
        s[strlen(s)-1]=0;//'\0',把每一行最后一个'\n'替换成'\0'

        if(strncmp(s,IPS,strlen(IPS))==0)
        {
            strcpy(dt->ips,s+strlen(IPS));
        }
        else if(strncmp(s,PORT,strlen(PORT))==0)
        {
            dt->port=atoi(s+strlen(PORT));
        }
        else if(strncmp(s,LISMAX,strlen(LISMAX))==0)
        {
            dt->lismax=atoi(s+strlen(LISMAX));
        }
        else
        {
            printf("不识别的参数:line %d\n",index);
        }


    }

    fclose(fp);
    return 0;

}
 
int socket_init()
{
    struct sock_info data;//定义一个结构体变量，接收信息
    if(read_sock_conf(&data)==-1)//把变量传递进去对其进行操作
    {
        return -1;
    }

   printf("ip=%s\n",data.ips);
   printf("port=%d\n",data.port);
   printf("lismax=%d\n",data.lismax);
   int sockfd=socket(AF_INET,SOCK_STREAM,0);
   if(sockfd==-1)
   {
       return -1;
   }

   struct sockaddr_in saddr;
   memset(&saddr,0,sizeof(saddr));
   saddr.sin_family=AF_INET;
   saddr.sin_port=htons(data.port);
   saddr.sin_addr.s_addr=inet_addr(data.ips);

   int res=bind(sockfd,(struct sockaddr*)&saddr,sizeof(saddr));
   if(res==-1)
   {
        return -1;
   }

   if(listen(sockfd,data.lismax)==-1)
   {
    return -1;
    }

    return sockfd;
}

